package com.heima.wemedia.service.impl;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.wemedia.dto.WnMaterialDto;
import com.heima.model.common.wemedia.pojo.WmMaterial;
import com.heima.model.common.wemedia.pojo.WmNewsMaterial;
import com.heima.utils.common.UserContext;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsMaterialService;
import com.jlefebure.spring.boot.minio.MinioException;
import com.jlefebure.spring.boot.minio.MinioService;
import org.apache.commons.io.FilenameUtils;
import org.apache.http.entity.ContentType;
import org.checkerframework.checker.nullness.qual.RequiresNonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author author
 * @since 2023-06-03
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private MinioService minioService;
    @Value("${spring.minio.url}")
    private String minioUrl;
    @Value("${spring.minio.bucket}")
    private String bucket;

    @Autowired
    private WmNewsMaterialService wmNewsMaterialService;

    /**
     * 素材文件上传
     *
     * @param multipartFile
     * @return
     * @throws Exception
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) throws Exception {
        if (multipartFile == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.将前端上传的文件保存到minio
        //1.1 获取前端上传文件的原始名称(aaa.jpg)
        String originalFilename = multipartFile.getOriginalFilename();
        //1.2 截取原始文件名中扩展名(jpg)。
        String extension = FilenameUtils.getExtension(originalFilename);
        String name = UUID.randomUUID().toString() + "." + extension;
        minioService.upload(Paths.get(name), multipartFile.getInputStream(), getImageContentType(extension));
        //http://192.168.200.130:9000/leadnews/name
        //2.调用mapper将素材的信息保存wm_material
        WmMaterial wmMaterial = new WmMaterial();
        Long userId = UserContext.getUserId();
        wmMaterial.setUserId(userId.intValue());
        String url = minioUrl + "/" + bucket + "/" + name;
        wmMaterial.setUrl(url);
        wmMaterial.setIsCollection(false);
        wmMaterial.setCreatedTime(LocalDateTime.now());
        save(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }


    public static ContentType getImageContentType(String extension) {
        Map<String,ContentType> map = new HashMap<>();
        map.put("jpg", ContentType.IMAGE_JPEG);
        map.put("png",ContentType.IMAGE_PNG);
        map.put("gif",ContentType.IMAGE_GIF);
        map.put("bmp",ContentType.IMAGE_BMP);
        map.put("tiff",ContentType.IMAGE_TIFF);
        map.put("webp",ContentType.IMAGE_WEBP);
        return map.get(extension);
    }

    /**
     * 自媒体图文素材分页查询
     */
    @Override
    public ResponseResult pager(WnMaterialDto dto) {
     dto.checkParam();
        IPage<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmMaterial> getWrapper = new LambdaQueryWrapper<>();
        Long userId = UserContext.getUserId();
        getWrapper.eq(WmMaterial::getUserId,userId);
        getWrapper.orderByDesc(WmMaterial::getCreatedTime);
        if(dto.getIsCollection()!=null&& dto.getIsCollection()==WmMaterial.CollStatus.COLLETO){
            getWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        page(page, getWrapper);
        List<WmMaterial> list = page.getRecords();
        long total = page.getTotal();
        return PageResponseResult.okResult(dto.getPage(),dto.getSize(),total,list);
    }

    /**
     * 收藏素材
     */
    @Override
    public ResponseResult collect(Integer id) {
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断素材是不是自己的，不是自己的不能改
        if (wmMaterial.getUserId().longValue()!=UserContext.getUserId().longValue()){
           return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        wmMaterial.setIsCollection(!wmMaterial.getIsCollection());
        updateById(wmMaterial);
        return ResponseResult.okResult();
    }


    /**
     * 删除素材
     */
    @Override
    public ResponseResult delete(Integer id) throws MinioException {
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断素材是不是自己的，不是自己的不能删
        if (wmMaterial.getUserId().longValue()!=UserContext.getUserId().longValue()){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getMaterialId,id);
        int count = wmNewsMaterialService.count(queryWrapper);
        if (count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        removeById(id);
        String name = FilenameUtils.getName(wmMaterial.getUrl());
        minioService.remove(Paths.get(name));
        return ResponseResult.okResult();
    }
}
